﻿namespace Leetcode.M0406;
public class Solution
{
    public TreeNode InorderSuccessor(TreeNode root, TreeNode p)
    {

        TreeNode ans = null;

        if (p.right == null)
        {
            var cur = root;
            while (cur != p)
            {
                if (p.val > cur.val)
                {
                    cur = cur.right;
                }
                else
                {
                    ans = cur;
                    cur = cur.left;
                }
            }
        }
        else
        {
            ans = p.right;
            while (ans.left != null)
            {
                ans = ans.left;
            }
        }
        return ans;
    }
}